// create an axios instance
const service = axios.create({
  baseURL: '',
  // withCredentials: true, // 当请求为跨域类型时是否在请求中协带cookie。
  timeout: 20000 // request timeout
})

// 设置请求次数，请求的间隙
service.defaults.retry = 4;
service.defaults.retryDelay = 1000;

// request interceptor
service.interceptors.request.use(
  config => {

    config.baseURL = '';
    // config.headers['Content-type'] = "application/x-www-form-urlencoded;charset=utf-8";

    var params = config.params || {};

    params.ts = (new Date()).getTime();
    
    config.params = params;

    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    var res = response.data
    if (res.code == 101) {
      alert('请登录账号');
      var href = location.protocol + '//' + location.host + "<?php echo url('/index/login);?>";
      location.href = href;
      return true;
    } else if (res.code == 102) {
      alert(res.message);
      location.href = location.origin;
      return true;
    }else {
      return res;
    }
  },
  error => {
    if (!error.response) {
      return new Promise(function (resolve, reject) {
        reject("Error_数据异常")
      }).catch(function () {
        return { code: 52001, message: "上传服务器错误" };
      })
    }
   
    const res = error.response.data
    if (error.response.status === 0) {
      Message({
        message: res.message || "Error_数据异常",
        type: 'error',
        duration: 5 * 1000
      })
    }
    
    return res;
    
  }
)